﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Abp.Domain.Repositories;
using Abp.ElasticSearch;
using AbpBuild;
using AbpBuild.LawManage;
using AbpBuild.WenShu;
using AbpBuild.WenShu.Dto;
using Newtonsoft.Json.Linq;

using System;
using DotnetSpider.Selector;
using System.Collections;
using Nest;
using System.Text.RegularExpressions;
using Abp.EntityFrameworkCore.Repositories;
using Microsoft.EntityFrameworkCore;
using Castle.DynamicProxy.Generators.Emitters.SimpleAST;
using Abp.Json;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Abp.Domain.Uow;
using System.Security.Policy;
using System.Web;
using Microsoft.AspNetCore.Mvc;
using System.Reflection;
using AbpBuild.BaseData;
using Castle.Core.Internal;
using AbpBuild.LawManage.Dto;
using Abp.Runtime.Caching;
using Abp.Application.Services;

namespace AbpBuild.LawManage
{


    /// <summary>
    /// 查询类
    /// </summary>
    public class LawSearshAppService : AbpBuildAppServiceBase, ILawSearshAppService
    {
        //private readonly IRepository<LawRecord, string> _lawrecordrepository; //in the first db
        //private readonly IRepository<LawRecordOther, int> _lawrecordotherrepository; //in the first db
        private AbpElasticSearch _abpElasticSearch;
        private Helpers _Helpers;
        private readonly ICacheManager _cacheManager;
        private BaseDatasHelper _baseDatasHelper;

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="lawrecordrepository"></param>
        /// <param name="lawrecordotherrepository"></param>
        /// <param name="abpElasticSearch"></param>
        /// <param name="helpers"></param>
        public LawSearshAppService(
            //IRepository<LawRecord, string> lawrecordrepository,
            //IRepository<LawRecordOther, int> lawrecordotherrepository,
            AbpElasticSearch abpElasticSearch,
            Helpers helpers,
            ICacheManager cacheManager,
            BaseDatasHelper baseDatasHelper
        )
        {
            //_lawrecordrepository = lawrecordrepository;
            //_lawrecordotherrepository = lawrecordotherrepository;
            _abpElasticSearch = abpElasticSearch;
            _Helpers = helpers;
            _cacheManager = cacheManager;
            _baseDatasHelper = baseDatasHelper;
        }

        /// <summary>
        /// 输入框模糊搜索
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<LawSearchOutParamDto> LawSearchForInputAsync(LawSearchParamDto input)
        {
            string cachestr = "SearchInput" + input.Data.name;
            var results = _cacheManager.GetCache("LawSearch").GetOrDefault(cachestr);
            if (results == null || !input.iscache)
            {
                input.Data.type = new List<string>();
                input.Data.type.Add("国家法律");
                input.Data.subtype = new List<string>();
                input.Data.subtype.Add("立法解释");
                input.Data.subtype.Add("部门规章");
                input.Data.subtype.Add("行政法规");
                input.Data.time_limited = new List<string>();
                input.Data.time_limited.Add("现行有效");
                input.Data.time_limited.Add("尚未生效");
                input.Data.eff_level = new List<string>();
                input.Data.eff_level.Add("法律-A02");

                //现行有效 失效   已被修改 尚未生效 部分失效 实际失效
                List<ISort> orders = new List<ISort>();
                //if (!string.IsNullOrEmpty(input.sortorder))
                //{
                //    //ISort sort = new FieldSort() { Field = input.sortorder, Order = (Nest.SortOrder?)input.Ascending };
                //    //ISort sort = new ScriptSort() { Order = Nest.SortOrder.Ascending, Script = new InlineScript("doc['name'].value.length()"),Type= "number" };
                //    //orders.Add(sort);
                //}
                //else
                //{
                ISort sort = new FieldSort() { Field = "posting_date", Order = Nest.SortOrder.Descending, UnmappedType = FieldType.Date };
                //ISort sort = new ScriptSort() { Order = (Nest.SortOrder?)input.Ascending, Script = new InlineScript("doc['name'].value.length()"),Type = "number" };
                orders.Add(sort);
                //}
                string[] highField = new string[] { "id", "name", "area", "authority", "effective_date", "posting_date", "document_number", "eff_level", "time_limited", "type", "subtype", "lawtype" };
                if (input.includeFields == null)
                {
                    input.includeFields = highField;
                }

                //if (input.size > 20)
                //{
                    input.size = 20;
                //}
                //if (!string.IsNullOrWhiteSpace(input.Data.name) && !string.IsNullOrEmpty(input.sortorder))
                //{
                //    size = 99999;
                //}
                //else
                //{
                //    size = input.size;
                //}
                var request = new SearchRequest("law")
                {
                    From = input.skip,
                    Size = input.size,
                    //Aggregations = new AggregationDictionary(), //聚合
                    Source = new SourceFilter()
                    {
                        Includes = input.includeFields
                        //Includes = new string[] { "eventid", "eventname" },
                        //Excludes = new string[] { "roginalid", "description" }
                    },
                    Sort = orders,
                    //TrackTotalHits = true
                };

                ///////////////////////
                QueryContainer querycontainer = SearchForInputParem(input);
                if (querycontainer != null)
                {
                    request.Query = querycontainer;
                }
                var his = await _abpElasticSearch.SearchAsync<LawSearchOutDTO, string>(request);

                string hightli = _Helpers.returnChina(input.ToJsonString());
                List<string> x = _abpElasticSearch.EsClient.Indices.Analyze(x => x.Analyzer("ik_smart").Text(hightli).Pretty()).Tokens.Select(p => p.Token).ToList();
                List<LawSearchOutDTO> Lawsearchoutdtos = new List<LawSearchOutDTO>();

                foreach (var item in his.Hits)
                {
                    LawSearchOutDTO enty = (LawSearchOutDTO)item.Source;
                    if (!string.IsNullOrEmpty(enty.Id))
                    {
                        _Helpers.ReturnhightTags(enty, x);
                    }
                    Lawsearchoutdtos.Add(enty);
                }

                LawSearchOutParamDto returnenty = new LawSearchOutParamDto();
                returnenty.Datas = Lawsearchoutdtos;
                returnenty.skip = input.skip;
                returnenty.size = input.size;
                returnenty.sortorder = input.sortorder;
                returnenty.Ascending = input.Ascending;
                //returnenty.counts = his.Total; //await _abpElasticSearch.CountAsync("law", request.Query);

                //if (querycontainer == null && input.skip == 0 && input.size == 10)
                //{
                _cacheManager.GetCache("LawSearch").Set(cachestr, returnenty, new TimeSpan(60, 0, 0, 0));
                //}

                return returnenty;
            }
            else
            {
                return (LawSearchOutParamDto)results;

            }

        }
        private QueryContainer SearchForInputParem(LawSearchParamDto input)
        {
            QueryContainer request = new QueryContainer();
            bool isnull = true;
            if (input.Data != null)
            {
                if (!string.IsNullOrEmpty(input.Data.name))
                {
                    string Alianame = input.Data.name.Replace("(", "（").Replace(")", "）").Replace(" ", "");
                    Alianame = Regex.Replace(Alianame, "（.*?）", "");
                    isnull = false;
                    request = request &&
                    new MatchQuery
                    {
                        Query = Alianame,
                        Field = new Field("name"),
                        Operator = Operator.And,
                        Analyzer = "ik_max_word"
                    };
                }
                if (input.Data.eff_level != null && input.Data.eff_level.Count > 0)
                {
                    isnull = false;
                    QueryContainer qc = new QueryContainer();
                    foreach (var item in input.Data.eff_level)
                    {
                        qc = qc 
                        || ( new TermQuery
                        {
                            Field = new Field("eff_level"),
                            Value = item.Replace(" ", "")
                        } 
                        && new ScriptQuery 
                        { 
                            Script = new InlineScript("doc['eff_level'].size() == 1") 
                        });
                    }
                    request = request && (qc);
                }
                if (input.Data.time_limited != null && input.Data.time_limited.Count > 0)
                {
                    isnull = false;
                    QueryContainer qc = new QueryContainer();
                    foreach (var item in input.Data.time_limited)
                    {
                        qc = qc || new TermQuery
                        {
                            Field = new Field("time_limited"),
                            Value = item.Replace(" ", "")
                        };
                    }
                    request = request && (qc);
                }
                if (input.Data.type != null && input.Data.type.Count > 0)
                {
                    isnull = false;
                    QueryContainer qc = new QueryContainer();
                    foreach (var item in input.Data.type)
                    {
                        qc = qc || new TermQuery
                        {
                            Field = new Field("type"),
                            Value = item.Replace(" ", "")
                        };
                    }
                    request = request && (qc);
                }
                if (input.Data.subtype != null && input.Data.subtype.Count > 0)
                {
                    isnull = false;
                    QueryContainer qc = new QueryContainer();
                    foreach (var item in input.Data.subtype)
                    {
                        qc = qc || new TermQuery
                        {
                            Field = new Field("subtype"),
                            Value = item.Replace(" ", "")
                        };
                    }
                    request = request && (qc);
                }
                
                if (isnull)
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
            return request;
        }

        #region law
        /// <summary>
        /// 法律查询列表
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        public async Task<LawSearchOutParamDto> LawSearchAsync(LawSearchParamDto input)
        {
            string cachestr = "LawSearchAsync" + Regex.Replace(input.ToJsonString(), "[^\u4e00-\u9fa5_a-zA-Z0-9]+", "");
            var results = _cacheManager.GetCache("LawSearch").GetOrDefault(cachestr);
            if (results == null || !input.iscache)
            {
                List<ISort> orders = new List<ISort>();
                //if (!string.IsNullOrEmpty(input.sortorder))
                //{
                //    //ISort sort = new FieldSort() { Field = input.sortorder, Order = (Nest.SortOrder?)input.Ascending };
                //    //ISort sort = new ScriptSort() { Order = Nest.SortOrder.Ascending, Script = new InlineScript("doc['name'].value.length()"),Type= "number" };
                //    //orders.Add(sort);
                //}
                //else
                //{
                    ISort sort = new FieldSort() { Field = "posting_date", Order = Nest.SortOrder.Descending, UnmappedType = FieldType.Date };
                    //ISort sort = new ScriptSort() { Order = (Nest.SortOrder?)input.Ascending, Script = new InlineScript("doc['name'].value.length()"),Type = "number" };
                    orders.Add(sort);
                //}
                string[] highField = new string[] { "id", "name", "area", "authority", "effective_date", "posting_date", "document_number", "eff_level", "time_limited", "type", "subtype", "lawtype" };
                if (input.includeFields == null)
                {
                    input.includeFields = highField;
                }

                if (input.size > 20)
                {
                    input.size = 20;
                }
                //if (!string.IsNullOrWhiteSpace(input.Data.name) && !string.IsNullOrEmpty(input.sortorder))
                //{
                //    size = 99999;
                //}
                //else
                //{
                //    size = input.size;
                //}
                var request = new SearchRequest("law")
                {
                    From = input.skip,
                    Size = input.size,
                    Aggregations = new AggregationDictionary(), //聚合
                    Source = new SourceFilter()
                    {
                        Includes = input.includeFields
                        //Includes = new string[] { "eventid", "eventname" },
                        //Excludes = new string[] { "roginalid", "description" }
                    },
                    Sort = orders,
                    TrackTotalHits = true
                };
            
                if (input.isagg)
                {
                    //聚合
                    #region
                    List<TermsOrder> orderArea = new List<TermsOrder>();
                    orderArea.Add(new TermsOrder() { Key = "_count", Order = Nest.SortOrder.Descending });//按数量//aggorder.Add(new TermsOrder() { Key = "_key", Order = Nest.SortOrder.Descending }); //按key
                    AggregationContainer aggArea = new TermsAggregation("aggArea")
                    {
                        Field = "area",
                        Size = 100,
                        Order = orderArea
                    };
                    request.Aggregations.Add("aggArea", aggArea);
                    //////////////////////////////////////////////////////////////////////////////////////////
                    List<TermsOrder> orderauthority = new List<TermsOrder>();
                    orderauthority.Add(new TermsOrder() { Key = "_count", Order = Nest.SortOrder.Descending });
                    AggregationContainer aggauthority = new TermsAggregation("aggauthority")
                    {
                        Field = "authority",
                        Size = 1012,
                        Order = orderauthority
                    };
                    request.Aggregations.Add("aggauthority", aggauthority);
                    ////////////////////////////////////////////////////////////////////////////////////////
                    AggregationContainer aggdate = new DateHistogramAggregation("aggdate")
                    {
                        Field = "posting_date",
                        Format = "yyyy",
                        CalendarInterval = new Union<DateInterval?, DateMathTime>(DateInterval.Year),
                        Order = HistogramOrder.KeyDescending,
                    };
                    request.Aggregations.Add("aggdate", aggdate);
                    //////////////////////////////////////////////////////////////////////////////////////////
                    List<TermsOrder> orderlevel = new List<TermsOrder>();
                    orderlevel.Add(new TermsOrder() { Key = "_count", Order = Nest.SortOrder.Descending });
                    AggregationContainer agglevel = new TermsAggregation("agglevel")
                    {
                        Field = "eff_level",
                        Size = 1000,
                        Order = orderlevel
                    };
                    request.Aggregations.Add("agglevel", agglevel);
                    //////////////////////////////////////////////////////////////////////////////////////////
                    List<TermsOrder> ordertype = new List<TermsOrder>();
                    ordertype.Add(new TermsOrder() { Key = "_count", Order = Nest.SortOrder.Descending });
                    AggregationContainer aggtype = new TermsAggregation("aggtype")
                    {
                        Field = "type",
                        Size = 100,
                        Order = ordertype
                    };
                    request.Aggregations.Add("aggtype", aggtype);
                    //////////////////////////////////////////////////////////////////////////////////////////
                    List<TermsOrder> ordersubtype = new List<TermsOrder>();
                    ordersubtype.Add(new TermsOrder() { Key = "_count", Order = Nest.SortOrder.Descending });
                    AggregationContainer aggsubtype = new TermsAggregation("aggsubtype")
                    {
                        Field = "subtype",
                        Size = 100,
                        Order = ordersubtype
                    };
                    request.Aggregations.Add("aggsubtype", aggsubtype);
                    //////////////////////////////////////////////////////////////////////////////////////////
                    List<TermsOrder> orderlawtype = new List<TermsOrder>();
                    orderlawtype.Add(new TermsOrder() { Key = "_count", Order = Nest.SortOrder.Descending });
                    AggregationContainer agglawtype = new TermsAggregation("agglawtype")
                    {
                        Field = "lawtype",
                        Size = 1000,
                        Order = orderlawtype
                    };
                    request.Aggregations.Add("agglawtype", agglawtype);
                    //////////////////////////////////////////////////////////////////////////////////////////
                    List<TermsOrder> ordertime_limited = new List<TermsOrder>();
                    ordertime_limited.Add(new TermsOrder() { Key = "_count", Order = Nest.SortOrder.Descending });
                    AggregationContainer aggtime_limited = new TermsAggregation("aggtime_limited")
                    {
                        Field = "time_limited",
                        Size = 1000,
                        Order = ordertime_limited
                    };
                    request.Aggregations.Add("aggtime_limited", aggtime_limited);


                    
                    #endregion
                }

                ///////////////////////
                QueryContainer querycontainer = SearchParem(input);
                if (querycontainer != null)
                {
                    request.Query = querycontainer;
                }
                var his = await _abpElasticSearch.SearchAsync<LawSearchOutDTO, string>(request);

                string hightli = _Helpers.returnChina(input.ToJsonString());
                List<string> x = _abpElasticSearch.EsClient.Indices.Analyze(x => x.Analyzer("ik_smart").Text(hightli).Pretty()).Tokens.Select(p => p.Token).ToList();
                List<LawSearchOutDTO> Lawsearchoutdtos = new List<LawSearchOutDTO>();

                foreach (var item in his.Hits)
                {
                    LawSearchOutDTO enty = (LawSearchOutDTO)item.Source;
                    if (!string.IsNullOrEmpty(enty.Id))
                    {
                        _Helpers.ReturnhightTags(enty, x);
                    }
                    Lawsearchoutdtos.Add(enty);
                }

                //if (!string.IsNullOrWhiteSpace(input.Data.name) && !string.IsNullOrEmpty(input.sortorder))
                //{
                //    rLawsearchoutdtos1 = Lawsearchoutdtos.Where(p=>p.name.Contains("中国人民共和国")).OrderBy(p => p.name.IndexOf("中国人民共和国")).ToList();
                //    rLawsearchoutdtos2 = Lawsearchoutdtos.Where(p=>!p.name.Contains("中国人民共和国")).ToList();
                //    rLawsearchoutdtos1.AddRange(rLawsearchoutdtos2);
                //    Lawsearchoutdtos = rLawsearchoutdtos1.Skip(input.skip).Take(input.size).ToList();
                //}
                
                LaWaggs agg = new LaWaggs();
                List<LawAuthority> laty = _baseDatasHelper.GetLawAuthorityOUT();
                List<LawType> lt = _baseDatasHelper.GetLawTypeOUT();
                List<Laweff_level> ll = _baseDatasHelper.GetLaweff_levelOUT();
                List<LawDXtype> lDX = _baseDatasHelper.GetLawDXtypeOUT();


                Dictionary<string, List<Dictionary<string, long?>>> aggs = new Dictionary<string, List<Dictionary<string, long?>>>();
                foreach (var item in his.Aggregations.Keys)
                {
                    var dd = his.Aggregations.GetValueOrDefault(item);
                    string types = dd.GetType().Name;
                    if (types == "SingleBucketAggregate")
                    {
                        foreach (var sl in ((Nest.SingleBucketAggregate)dd).Values)
                        {
                            List<Dictionary<string, long?>> templ = new List<Dictionary<string, long?>>();
                            foreach (var ts in ((Nest.BucketAggregate)sl).Items)
                            {
                                Dictionary<string, long?> tempd = new Dictionary<string, long?>();
                                tempd.Add(((Nest.KeyedBucket<object>)ts).Key.ToString(), ((Nest.KeyedBucket<object>)ts).DocCount);
                                templ.Add(tempd);
                            }
                            aggs.Add(item, templ);
                        }
                    }
                    else
                    {
                        List<Dictionary<string, long?>> templ = new List<Dictionary<string, long?>>();

                        foreach (var ts in ((Nest.BucketAggregate)dd).Items)
                        {

                            if (item == "aggdate")
                            {
                                Dictionary<string, long?> tempd = new Dictionary<string, long?>();
                                tempd.Add(((Nest.KeyedBucket<double>)ts).KeyAsString, ((Nest.KeyedBucket<double>)ts).DocCount);
                                templ.Add(tempd);
                            }
                            else if (item == "aggauthority")
                            {
                                string key = ((Nest.KeyedBucket<object>)ts).Key.ToString();
                                long? count = ((Nest.KeyedBucket<object>)ts).DocCount;
                                LawAuthority cr = laty.Where(p => p.Id == key.Split('-')[1]).FirstOrDefault();
                                if (cr != null)
                                {
                                    cr.count = count;
                                }
                            }
                            else if (item == "agglawtype")
                            {
                                string key = ((Nest.KeyedBucket<object>)ts).Key.ToString();
                                long? count = ((Nest.KeyedBucket<object>)ts).DocCount;
                                LawType cr = lt.Where(p => p.Id == key.Split('-')[1]).FirstOrDefault();
                                if (cr != null)
                                {
                                    cr.count = count;
                                }
                            }
                            else if (item == "agglevel")
                            {
                                string key = ((Nest.KeyedBucket<object>)ts).Key.ToString();
                                long? count = ((Nest.KeyedBucket<object>)ts).DocCount;
                                Laweff_level cr = ll.Where(p => p.Id == key.Split('-')[1]).FirstOrDefault();
                                if (cr != null)
                                {
                                    cr.count = count;
                                }
                            }
                            else if (item == "aggtype")
                            {
                                string key = ((Nest.KeyedBucket<object>)ts).Key.ToString();
                                long? count = ((Nest.KeyedBucket<object>)ts).DocCount;
                                LawDXtype cr = lDX.Where(p => p.name == key).FirstOrDefault();
                                if (cr != null)
                                {
                                    cr.count = count;
                                }
                            }
                            else if (item == "aggsubtype")
                            {
                                string key = ((Nest.KeyedBucket<object>)ts).Key.ToString();
                                long? count = ((Nest.KeyedBucket<object>)ts).DocCount;
                                LawDXtype cr = lDX.Where(p => p.name == key).FirstOrDefault();
                                if (cr != null)
                                {
                                    cr.count = count;
                                }
                            }

                            else
                            {
                                Dictionary<string, long?> tempd = new Dictionary<string, long?>();
                                tempd.Add(((Nest.KeyedBucket<object>)ts).Key.ToString(), ((Nest.KeyedBucket<object>)ts).DocCount);
                                templ.Add(tempd);
                            }
                            
                        }
                        if (templ.Count > 0)
                        {
                            aggs.Add(item, templ);
                        }
                    }
                }

                //··
                laty = laty.Where(p => p.count > 0).ToList();
                List<LawAuthority> laaaa = laty.Where(p => p.levels == 1).ToList();
                for (int i = 0; i < laaaa.Count; i++)
                {
                    if (laaaa[i].childLawAuthority != null && laaaa[i].childLawAuthority.Count > 0)
                    {
                        List<LawAuthority> ljps1 = laaaa[i].childLawAuthority.ToList();
                        for (int i1 = 0; i1 < ljps1.Count; i1++)
                        {
                            LawAuthority crt1 = laty.Where(p => p.Id == ljps1[i1].Id).FirstOrDefault();
                            if (crt1 != null)
                            {
                                ljps1[i1].count = crt1.count;
                                if (ljps1[i1].childLawAuthority != null && ljps1[i1].childLawAuthority.Count > 0)
                                {
                                    List<LawAuthority> ljps2 = ljps1[i1].childLawAuthority.ToList();
                                    for (int i2 = 0; i2 < ljps2.Count; i2++)
                                    {
                                        LawAuthority crt3 = laty.Where(p => p.Id == ljps2[i2].Id).FirstOrDefault();
                                        if (crt3 != null)
                                        {
                                            ljps2[i2].count = crt3.count;
                                            if (ljps2[i2].childLawAuthority != null && ljps2[i2].childLawAuthority.Count > 0)
                                            {
                                                List<LawAuthority> ljps3 = ljps2[i2].childLawAuthority.ToList();
                                                for (int i3 = 0; i3 < ljps3.Count; i3++)
                                                {
                                                    LawAuthority crt4 = laty.Where(p => p.Id == ljps3[i3].Id).FirstOrDefault();
                                                    if (crt4 != null)
                                                    {
                                                        ljps3[i3].count = crt4.count;
                                                        if (ljps3[i3].childLawAuthority != null && ljps3[i3].childLawAuthority.Count > 0)
                                                        {
                                                            List<LawAuthority> ljps4 = ljps3[i3].childLawAuthority.ToList();
                                                            for (int i4 = 0; i4 < ljps4.Count; i4++)
                                                            {
                                                                LawAuthority crt5 = laty.Where(p => p.Id == ljps4[i4].Id).FirstOrDefault();
                                                                if (crt5 != null)
                                                                {
                                                                    ljps4[i4].count = crt5.count;
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                for (int i = 0; i < laaaa.Count; i++)
                {
                    if (laaaa[i].count == null || laaaa[i].count == 0)
                    {
                        laaaa.Remove(laaaa[i]);
                    }
                    else
                    {
                        if (laaaa[i].childLawAuthority != null && laaaa[i].childLawAuthority.Count > 0)
                        {
                            List<LawAuthority> crs1 = laaaa[i].childLawAuthority.ToList();
                            for (int i1 = 0; i1 < crs1.Count; i1++)
                            {
                                if (crs1[i1].count == null || crs1[i1].count == 0)
                                {
                                    laaaa[i].childLawAuthority.Remove(crs1[i1]);
                                }
                                else
                                {
                                    if (crs1[i1].childLawAuthority != null && crs1[i1].childLawAuthority.Count > 0)
                                    {
                                        List<LawAuthority> crs2 = crs1[i1].childLawAuthority.ToList();
                                        for (int i2 = 0; i2 < crs2.Count; i2++)
                                        {
                                            if (crs2[i2].count == null || crs2[i2].count == 0)
                                            {
                                                crs1[i1].childLawAuthority.Remove(crs2[i2]);
                                            }
                                            else
                                            {
                                                if (crs2[i2].childLawAuthority != null && crs2[i2].childLawAuthority.Count > 0)
                                                {
                                                    List<LawAuthority> crs3 = crs2[i2].childLawAuthority.ToList();
                                                    for (int i3 = 0; i3 < crs3.Count; i3++)
                                                    {
                                                        if (crs3[i3].count == null || crs3[i3].count == 0)
                                                        {
                                                            crs2[i2].childLawAuthority.Remove(crs3[i3]);
                                                        }
                                                        else
                                                        {
                                                            if (crs3[i3].childLawAuthority != null && crs3[i3].childLawAuthority.Count > 0)
                                                            {
                                                                List<LawAuthority> crs4 = crs3[i3].childLawAuthority.ToList();
                                                                for (int i4 = 0; i4 < crs4.Count; i4++)
                                                                {
                                                                    if (crs4[i4].count == null || crs4[i4].count == 0)
                                                                    {
                                                                        crs3[i3].childLawAuthority.Remove(crs4[i4]);
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }

                                                }
                                            }
                                        }

                                    }
                                }
                            }

                        }
                    }
                }
                //··
                //··
                lt = lt.Where(p => p.count > 0).ToList();
                List<LawType> ltaaa = lt.Where(p => p.levels == 1).ToList();
                for (int i = 0; i < ltaaa.Count; i++)
                {
                    if (ltaaa[i].childLawType != null && ltaaa[i].childLawType.Count > 0)
                    {
                        List<LawType> ljps1 = ltaaa[i].childLawType.ToList();
                        for (int i1 = 0; i1 < ljps1.Count; i1++)
                        {
                            LawType crt1 = lt.Where(p => p.Id == ljps1[i1].Id).FirstOrDefault();
                            if (crt1 != null)
                            {
                                ljps1[i1].count = crt1.count;
                                if (ljps1[i1].childLawType != null && ljps1[i1].childLawType.Count > 0)
                                {
                                    List<LawType> ljps2 = ljps1[i1].childLawType.ToList();
                                    for (int i2 = 0; i2 < ljps2.Count; i2++)
                                    {
                                        LawType crt3 = lt.Where(p => p.Id == ljps2[i2].Id).FirstOrDefault();
                                        if (crt3 != null)
                                        {
                                            ljps2[i2].count = crt3.count;
                                            if (ljps2[i2].childLawType != null && ljps2[i2].childLawType.Count > 0)
                                            {
                                                List<LawType> ljps3 = ljps2[i2].childLawType.ToList();
                                                for (int i3 = 0; i3 < ljps3.Count; i3++)
                                                {
                                                    LawType crt4 = lt.Where(p => p.Id == ljps3[i3].Id).FirstOrDefault();
                                                    if (crt4 != null)
                                                    {
                                                        ljps3[i3].count = crt4.count;
                                                        if (ljps3[i3].childLawType != null && ljps3[i3].childLawType.Count > 0)
                                                        {
                                                            List<LawType> ljps4 = ljps3[i3].childLawType.ToList();
                                                            for (int i4 = 0; i4 < ljps4.Count; i4++)
                                                            {
                                                                LawType crt5 = lt.Where(p => p.Id == ljps4[i4].Id).FirstOrDefault();
                                                                if (crt5 != null)
                                                                {
                                                                    ljps4[i4].count = crt5.count;
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                for (int i = 0; i < ltaaa.Count; i++)
                {
                    if (ltaaa[i].count == null || ltaaa[i].count == 0)
                    {
                        ltaaa.Remove(ltaaa[i]);
                    }
                    else
                    {
                        if (ltaaa[i].childLawType != null && ltaaa[i].childLawType.Count > 0)
                        {
                            List<LawType> crs1 = ltaaa[i].childLawType.ToList();
                            for (int i1 = 0; i1 < crs1.Count; i1++)
                            {
                                if (crs1[i1].count == null || crs1[i1].count == 0)
                                {
                                    ltaaa[i].childLawType.Remove(crs1[i1]);
                                }
                                else
                                {
                                    if (crs1[i1].childLawType != null && crs1[i1].childLawType.Count > 0)
                                    {
                                        List<LawType> crs2 = crs1[i1].childLawType.ToList();
                                        for (int i2 = 0; i2 < crs2.Count; i2++)
                                        {
                                            if (crs2[i2].count == null || crs2[i2].count == 0)
                                            {
                                                crs1[i1].childLawType.Remove(crs2[i2]);
                                            }
                                            else
                                            {
                                                if (crs2[i2].childLawType != null && crs2[i2].childLawType.Count > 0)
                                                {
                                                    List<LawType> crs3 = crs2[i2].childLawType.ToList();
                                                    for (int i3 = 0; i3 < crs3.Count; i3++)
                                                    {
                                                        if (crs3[i3].count == null || crs3[i3].count == 0)
                                                        {
                                                            crs2[i2].childLawType.Remove(crs3[i3]);
                                                        }
                                                        else
                                                        {
                                                            if (crs3[i3].childLawType != null && crs3[i3].childLawType.Count > 0)
                                                            {
                                                                List<LawType> crs4 = crs3[i3].childLawType.ToList();
                                                                for (int i4 = 0; i4 < crs4.Count; i4++)
                                                                {
                                                                    if (crs4[i4].count == null || crs4[i4].count == 0)
                                                                    {
                                                                        crs3[i3].childLawType.Remove(crs4[i4]);
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }

                                                }
                                            }
                                        }

                                    }
                                }
                            }

                        }
                    }
                }
                //··
                //··
                ll = ll.Where(p => p.count > 0).ToList();
                List<Laweff_level> ljaaa = ll.Where(p => p.levels == 1).ToList();
                for (int i = 0; i < ljaaa.Count; i++)
                {
                    if (ljaaa[i].childLaweff_level != null && ljaaa[i].childLaweff_level.Count > 0)
                    {
                        List<Laweff_level> ljps1 = ljaaa[i].childLaweff_level.ToList();
                        for (int i1 = 0; i1 < ljps1.Count; i1++)
                        {
                            Laweff_level crt1 = ll.Where(p => p.Id == ljps1[i1].Id).FirstOrDefault();
                            if (crt1 != null)
                            {
                                ljps1[i1].count = crt1.count;
                                if (ljps1[i1].childLaweff_level != null && ljps1[i1].childLaweff_level.Count > 0)
                                {
                                    List<Laweff_level> ljps2 = ljps1[i1].childLaweff_level.ToList();
                                    for (int i2 = 0; i2 < ljps2.Count; i2++)
                                    {
                                        Laweff_level crt3 = ll.Where(p => p.Id == ljps2[i2].Id).FirstOrDefault();
                                        if (crt3 != null)
                                        {
                                            ljps2[i2].count = crt3.count;
                                            if (ljps2[i2].childLaweff_level != null && ljps2[i2].childLaweff_level.Count > 0)
                                            {
                                                List<Laweff_level> ljps3 = ljps2[i2].childLaweff_level.ToList();
                                                for (int i3 = 0; i3 < ljps3.Count; i3++)
                                                {
                                                    Laweff_level crt4 = ll.Where(p => p.Id == ljps3[i3].Id).FirstOrDefault();
                                                    if (crt4 != null)
                                                    {
                                                        ljps3[i3].count = crt4.count;
                                                        if (ljps3[i3].childLaweff_level != null && ljps3[i3].childLaweff_level.Count > 0)
                                                        {
                                                            List<Laweff_level> ljps4 = ljps3[i3].childLaweff_level.ToList();
                                                            for (int i4 = 0; i4 < ljps4.Count; i4++)
                                                            {
                                                                Laweff_level crt5 = ll.Where(p => p.Id == ljps4[i4].Id).FirstOrDefault();
                                                                if (crt5 != null)
                                                                {
                                                                    ljps4[i4].count = crt5.count;
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                for (int i = 0; i < ljaaa.Count; i++)
                {
                    if (ljaaa[i].count == null || ljaaa[i].count == 0)
                    {
                        ljaaa.Remove(ljaaa[i]);
                    }
                    else
                    {
                        if (ljaaa[i].childLaweff_level != null && ljaaa[i].childLaweff_level.Count > 0)
                        {
                            List<Laweff_level> crs1 = ljaaa[i].childLaweff_level.ToList();
                            for (int i1 = 0; i1 < crs1.Count; i1++)
                            {
                                if (crs1[i1].count == null || crs1[i1].count == 0)
                                {
                                    ljaaa[i].childLaweff_level.Remove(crs1[i1]);
                                }
                                else
                                {
                                    if (crs1[i1].childLaweff_level != null && crs1[i1].childLaweff_level.Count > 0)
                                    {
                                        List<Laweff_level> crs2 = crs1[i1].childLaweff_level.ToList();
                                        for (int i2 = 0; i2 < crs2.Count; i2++)
                                        {
                                            if (crs2[i2].count == null || crs2[i2].count == 0)
                                            {
                                                crs1[i1].childLaweff_level.Remove(crs2[i2]);
                                            }
                                            else
                                            {
                                                if (crs2[i2].childLaweff_level != null && crs2[i2].childLaweff_level.Count > 0)
                                                {
                                                    List<Laweff_level> crs3 = crs2[i2].childLaweff_level.ToList();
                                                    for (int i3 = 0; i3 < crs3.Count; i3++)
                                                    {
                                                        if (crs3[i3].count == null || crs3[i3].count == 0)
                                                        {
                                                            crs2[i2].childLaweff_level.Remove(crs3[i3]);
                                                        }
                                                        else
                                                        {
                                                            if (crs3[i3].childLaweff_level != null && crs3[i3].childLaweff_level.Count > 0)
                                                            {
                                                                List<Laweff_level> crs4 = crs3[i3].childLaweff_level.ToList();
                                                                for (int i4 = 0; i4 < crs4.Count; i4++)
                                                                {
                                                                    if (crs4[i4].count == null || crs4[i4].count == 0)
                                                                    {
                                                                        crs3[i3].childLaweff_level.Remove(crs4[i4]);
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }

                                                }
                                            }
                                        }

                                    }
                                }
                            }

                        }
                    }
                }
                //··
                //··
                lDX = lDX.Where(p => p.count > 0).ToList();
                List<LawDXtype> ljpLevels = lDX.Where(p => p.levels == 1).ToList();
                for (int i = 0; i < ljpLevels.Count; i++)
                {
                    if (ljpLevels[i].childLawDXtype != null && ljpLevels[i].childLawDXtype.Count > 0)
                    {
                        List<LawDXtype> ljps1 = ljpLevels[i].childLawDXtype.ToList();
                        for (int i1 = 0; i1 < ljps1.Count; i1++)
                        {
                            LawDXtype crt1 = lDX.Where(p => p.Id == ljps1[i1].Id).FirstOrDefault();
                            if (crt1 != null)
                            {
                                ljps1[i1].count = crt1.count;
                                if (ljps1[i1].childLawDXtype != null && ljps1[i1].childLawDXtype.Count > 0)
                                {
                                    List<LawDXtype> ljps2 = ljps1[i1].childLawDXtype.ToList();
                                    for (int i2 = 0; i2 < ljps2.Count; i2++)
                                    {
                                        LawDXtype crt3 = lDX.Where(p => p.Id == ljps2[i2].Id).FirstOrDefault();
                                        if (crt3 != null)
                                        {
                                            ljps2[i2].count = crt3.count;
                                            if (ljps2[i2].childLawDXtype != null && ljps2[i2].childLawDXtype.Count > 0)
                                            {
                                                List<LawDXtype> ljps3 = ljps2[i2].childLawDXtype.ToList();
                                                for (int i3 = 0; i3 < ljps3.Count; i3++)
                                                {
                                                    LawDXtype crt4 = lDX.Where(p => p.Id == ljps3[i3].Id).FirstOrDefault();
                                                    if (crt4 != null)
                                                    {
                                                        ljps3[i3].count = crt4.count;
                                                        if (ljps3[i3].childLawDXtype != null && ljps3[i3].childLawDXtype.Count > 0)
                                                        {
                                                            List<LawDXtype> ljps4 = ljps3[i3].childLawDXtype.ToList();
                                                            for (int i4 = 0; i4 < ljps4.Count; i4++)
                                                            {
                                                                LawDXtype crt5 = lDX.Where(p => p.Id == ljps4[i4].Id).FirstOrDefault();
                                                                if (crt5 != null)
                                                                {
                                                                    ljps4[i4].count = crt5.count;
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                for (int i = 0; i < ljpLevels.Count; i++)
                {
                    if (ljpLevels[i].count == null || ljpLevels[i].count == 0)
                    {
                        ljpLevels.Remove(ljpLevels[i]);
                    }
                    else
                    {
                        if (ljpLevels[i].childLawDXtype != null && ljpLevels[i].childLawDXtype.Count > 0)
                        {
                            List<LawDXtype> crs1 = ljpLevels[i].childLawDXtype.ToList();
                            for (int i1 = 0; i1 < crs1.Count; i1++)
                            {
                                if (crs1[i1].count == null || crs1[i1].count == 0)
                                {
                                    ljpLevels[i].childLawDXtype.Remove(crs1[i1]);
                                }
                                else
                                {
                                    if (crs1[i1].childLawDXtype != null && crs1[i1].childLawDXtype.Count > 0)
                                    {
                                        List<LawDXtype> crs2 = crs1[i1].childLawDXtype.ToList();
                                        for (int i2 = 0; i2 < crs2.Count; i2++)
                                        {
                                            if (crs2[i2].count == null || crs2[i2].count == 0)
                                            {
                                                crs1[i1].childLawDXtype.Remove(crs2[i2]);
                                            }
                                            else
                                            {
                                                if (crs2[i2].childLawDXtype != null && crs2[i2].childLawDXtype.Count > 0)
                                                {
                                                    List<LawDXtype> crs3 = crs2[i2].childLawDXtype.ToList();
                                                    for (int i3 = 0; i3 < crs3.Count; i3++)
                                                    {
                                                        if (crs3[i3].count == null || crs3[i3].count == 0)
                                                        {
                                                            crs2[i2].childLawDXtype.Remove(crs3[i3]);
                                                        }
                                                        else
                                                        {
                                                            if (crs3[i3].childLawDXtype != null && crs3[i3].childLawDXtype.Count > 0)
                                                            {
                                                                List<LawDXtype> crs4 = crs3[i3].childLawDXtype.ToList();
                                                                for (int i4 = 0; i4 < crs4.Count; i4++)
                                                                {
                                                                    if (crs4[i4].count == null || crs4[i4].count == 0)
                                                                    {
                                                                        crs3[i3].childLawDXtype.Remove(crs4[i4]);
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }

                                                }
                                            }
                                        }

                                    }
                                }
                            }

                        }
                    }
                }
                //··


                agg.agg = aggs;
                agg.laty = laaaa;
                agg.lt = ltaaa;
                agg.ll = ljaaa;
                agg.lDX = ljpLevels;

                LawSearchOutParamDto returnenty = new LawSearchOutParamDto();
                returnenty.Datas = Lawsearchoutdtos;
                returnenty.aggs = agg;
                returnenty.skip = input.skip;
                returnenty.size = input.size;
                returnenty.sortorder = input.sortorder;
                returnenty.Ascending = input.Ascending;
                returnenty.counts = his.Total; //await _abpElasticSearch.CountAsync("law", request.Query);

                //if (querycontainer == null && input.skip == 0 && input.size == 10)
                //{
                    _cacheManager.GetCache("LawSearch").Set(cachestr, returnenty, new TimeSpan(60, 0, 0, 0));
                //}

                return returnenty;
            }
            else
            {
                return (LawSearchOutParamDto)results;

            }

        }
        /// <summary>
        /// 组装条件
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private QueryContainer SearchParem(LawSearchParamDto input)
        {
            QueryContainer request = new QueryContainer();
            bool isnull = true;
            if (input.Data != null)
            {
                if (!string.IsNullOrEmpty(input.Data.name))
                {
                    string Alianame = input.Data.name.Replace("(", "（").Replace(")", "）").Replace(" ", "");
                     Alianame = Regex.Replace(Alianame, "（.*?）","");

                    //if (!string.IsNullOrEmpty(input.sortorder))
                    //{
                    //    if (Alianame.Contains("中华人民共和国"))
                    //    {

                    //    }
                    //}

                    isnull = false;
                    request = request &&
                    new MatchQuery
                    {
                        Query = Alianame,
                        Field = new Field("name"),
                        Operator = Operator.And,
                        Analyzer = "ik_max_word"
                    };
                }
                if (input.Data.area != null && input.Data.area.Count > 0)
                {
                    isnull = false;
                    QueryContainer qc = new QueryContainer();
                    foreach (var item in input.Data.area)
                    {
                        qc = qc || new TermQuery
                        {
                            Field = new Field("area"),
                            Value = item.Replace(" ", "")
                        };
                    }
                    request = request && (qc);
                }
                if (!string.IsNullOrEmpty(input.Data.authority))
                {
                    isnull = false;
                    QueryContainer qc = new QueryContainer();
                    qc = qc &&
                    new TermQuery
                    {
                        Field = new Field("authority"),
                        Value = input.Data.authority.Replace(" ", "")
                    };
                    request = request && (qc);
                }

                if (input.Data.effective_dateS != null)
                {
                    isnull = false;
                    request = request &&
                    new DateRangeQuery()
                    {
                        Field = new Field("effective_date"),
                        GreaterThanOrEqualTo = input.Data.effective_dateS
                    };
                }
                if (input.Data.effective_dateE != null)
                {
                    isnull = false;
                    request = request &&
                    new DateRangeQuery()
                    {
                        Field = new Field("effective_date"),
                        LessThanOrEqualTo = input.Data.effective_dateE
                    };
                }

                if (input.Data.posting_dateS != null)
                {
                    isnull = false;
                    request = request &&
                    new DateRangeQuery()
                    {
                        Field = new Field("posting_date"),
                        GreaterThanOrEqualTo = input.Data.posting_dateS
                    };
                }
                if (input.Data.posting_dateE != null)
                {
                    isnull = false;
                    request = request &&
                    new DateRangeQuery()
                    {
                        Field = new Field("posting_date"),
                        LessThanOrEqualTo = input.Data.posting_dateE
                    };
                }


                if (!string.IsNullOrEmpty(input.Data.document_number))
                {
                    isnull = false;
                    QueryContainer qc = new QueryContainer();
                    qc = qc &&
                    new TermQuery
                    {
                        Field = new Field("document_number"),
                        Value = input.Data.document_number.Replace(" ", "")
                    };
                    request = request && (qc);
                }

                if (input.Data.eff_level != null && input.Data.eff_level.Count > 0)
                {
                    isnull = false;
                    QueryContainer qc = new QueryContainer();
                    foreach (var item in input.Data.eff_level)
                    {
                        qc = qc || new TermQuery
                        {
                            Field = new Field("eff_level"),
                            Value = item.Replace(" ", "")
                        };
                    }
                    request = request && (qc);
                }
                if (input.Data.time_limited != null && input.Data.time_limited.Count > 0)
                {
                    isnull = false;
                    QueryContainer qc = new QueryContainer();
                    foreach (var item in input.Data.time_limited)
                    {
                        qc = qc || new TermQuery
                        {
                            Field = new Field("time_limited"),
                            Value = item.Replace(" ", "")
                        };
                    }
                    request = request && (qc);
                }
                if (input.Data.type != null && input.Data.type.Count > 0)
                {
                    isnull = false;
                    QueryContainer qc = new QueryContainer();
                    foreach (var item in input.Data.type)
                    {
                        qc = qc || new TermQuery
                        {
                            Field = new Field("type"),
                            Value = item.Replace(" ", "")
                        };
                    }
                    request = request && (qc);
                }
                if (input.Data.subtype != null && input.Data.subtype.Count > 0)
                {
                    isnull = false;
                    QueryContainer qc = new QueryContainer();
                    foreach (var item in input.Data.subtype)
                    {
                        qc = qc || new TermQuery
                        {
                            Field = new Field("subtype"),
                            Value = item.Replace(" ", "")
                        };
                    }
                    request = request && (qc);
                }
                if (input.Data.lawtype != null && input.Data.lawtype.Count > 0)
                {
                    isnull = false;
                    QueryContainer qc = new QueryContainer();
                    foreach (var item in input.Data.lawtype)
                    {
                        qc = qc || new TermQuery
                        {
                            Field = new Field("lawtype"),
                            Value = item.Replace(" ", "")
                        };
                    }
                    request = request && (qc);
                }

                if (isnull)
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
            return request;
        }
        /// <summary>
        /// 获取法律详情
        /// </summary>
        /// <param name="id">id</param>
        /// <param name="hightTags">查询的条件，高亮显示</param>
        /// <returns></returns>
        public async Task<LawTotalSearchOutDTO> GetLawDetail(string id, string hightTags = null)
        {
            try
            {
                string cachestr = "GetLawDetail" + id;
                var results = _cacheManager.GetCache("LawSearch").GetOrDefault(cachestr);
                if (results == null)
                {
                    LawTotalSearchOutDTO LawTotalSearchOutDTO = new LawTotalSearchOutDTO();
                    //string ss = "依照《中华人民共和国合同法》二百零六条第四项,第二百零七条、多多《最高人民法院关于适用〈中华人民共和国民事诉讼法〉的解释》第二十七条.第一百七十条第一款第一项，手动阀《中华人民共和国民事诉讼法》第一百四十四条之规定阀手动阀依照《中华人民共和国民事诉讼法》第一条，《中华人民共和国合同法》第二百零六条第四项、第二百零七条、第二十七条，第一百七十条第一款第一项，、第二十七条、第二十七条、第二十七条、第二十七条、第一百四十四条之规定阀手动阀";
                    //string sss = new Helpers().returnLawsTag(ss, "<a", "</a>");
                    QueryContainer qc = new QueryContainer();
                    Id id1 = new Id(id);
                    List<Id> ids = new List<Id>();
                    ids.Add(id1);
                    qc = qc || new IdsQuery
                    {
                        Values = ids
                    };
                    var request = new SearchRequest("law")
                    {
                        Query = qc
                    };
                    var his = await _abpElasticSearch.SearchAsync<LawSearchOutDTO, string>(request);

                    if (hightTags != null)
                    {
                        string hightli = _Helpers.returnChina(System.Web.HttpUtility.UrlDecode(hightTags).Replace(":", "的"));
                        List<string> x = _abpElasticSearch.EsClient.Indices.Analyze(x => x.Analyzer("ik_smart").Text(hightli).Pretty()).Tokens.Select(p => p.Token).ToList();
                        foreach (var item in his.Hits)
                        {
                            LawSearchOutDTO enty = (LawSearchOutDTO)item.Source;
                            if (!string.IsNullOrEmpty(enty.Id))
                            {
                                _Helpers.ReturnDetailTagsALL(enty, x);
                                LawTotalSearchOutDTO.lawsearchoutdto = enty;
                            }
                        }
                    }
                    else
                    {
                        foreach (var item in his.Hits)
                        {
                            LawSearchOutDTO enty = (LawSearchOutDTO)item.Source;
                            if (!string.IsNullOrEmpty(enty.Id))
                            {
                                LawTotalSearchOutDTO.lawsearchoutdto = enty;
                            }
                        }
                    }
                    LawDetailSearchInDTO detailinput = new LawDetailSearchInDTO();
                    detailinput.pid = new List<string>();
                    detailinput.pid.Add(LawTotalSearchOutDTO.lawsearchoutdto.Id);
                    detailinput.ishilhlit = 1;
                    List<LawDetailSearchOutDTO> LawDetailSearchOutDTOs = await LawDetailSearchAsync(detailinput);
                    LawTotalSearchOutDTO.lawdetailrecordsearchoutdtos = LawDetailSearchOutDTOs;

                    _cacheManager.GetCache("LawSearch").Set(cachestr, LawTotalSearchOutDTO, new TimeSpan(60, 0, 0, 0));

                    return LawTotalSearchOutDTO;
                }
                else
                {
                    return (LawTotalSearchOutDTO)results;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        #endregion

        #region lawtiao
        [RemoteService(false)]
        public List<LawDetailSearchOutDTO> LawDetailSearch2(LawDetailSearchInDTO input)
        {
            string cachestr = "LawDetailSearch2" + Regex.Replace(input.ToJsonString(), "[^\u4e00-\u9fa5_a-zA-Z0-9]+", "");
            var results = _cacheManager.GetCache("LawSearch").GetOrDefault(cachestr);
            if (results == null || !input.iscache)
            {
                List<ISort> orders = new List<ISort>();
                ISort sort1 = new FieldSort() { Field = "effective_date", Order = Nest.SortOrder.Descending, UnmappedType = FieldType.Date };
                ISort sort = new FieldSort() { Field = "order", Order = Nest.SortOrder.Ascending, UnmappedType = FieldType.Long };
                orders.Add(sort1);
                orders.Add(sort);
                //sort


                var request = new SearchRequest("lawdetail")
                {
                    From = 0,
                    Size = 9999,
                    Source = new SourceFilter()
                    {
                        Includes = new string[] { "id", "name", "tiaoint", "tiao", "text", "order", "Lawdetailotherinputdtos" }
                        //Includes = new string[] { "eventid", "eventname" },
                        //Excludes = new string[] { "roginalid", "description" }
                    },
                    Sort = orders
                };

                ///////////////////////
                QueryContainer querycontainer = SearchParem(input);
                if (querycontainer != null)
                {
                    request.Query = querycontainer;
                }
                var his = _abpElasticSearch.Search<LawDetailSearchOutDTO, string>(request);

                string hightli = _Helpers.returnChina(input.ToJsonString().Replace(":", "的"));
                List<string> x = _abpElasticSearch.EsClient.Indices.Analyze(x => x.Analyzer("ik_smart").Text(hightli).Pretty()).Tokens.Select(p => p.Token).ToList();
                List<LawDetailSearchOutDTO> lawdetailsearchoutdtos = new List<LawDetailSearchOutDTO>();
                foreach (var item in his.Hits)
                {
                    LawDetailSearchOutDTO enty = (LawDetailSearchOutDTO)item.Source;
                    if (!string.IsNullOrEmpty(enty.Id))
                    {
                        _Helpers.ReturnhightTags(enty, x);
                    }
                    lawdetailsearchoutdtos.Add(enty);
                }
                _cacheManager.GetCache("LawSearch").Set(cachestr, lawdetailsearchoutdtos, new TimeSpan(60, 0, 0, 0));
                return lawdetailsearchoutdtos;
            }
            else
            {
                return (List<LawDetailSearchOutDTO>)results;
            }
        }



        /// <summary>
        /// 查询获取法条
        /// </summary>
        /// <param name="input">条件</param>
        /// <returns>列表</returns>
        [RemoteService(false)]
        public async Task<List<LawDetailSearchOutDTO>> LawDetailSearchAsync(LawDetailSearchInDTO input)
        {
            string cachestr = "LawDetailSearchAsync" + Regex.Replace(input.ToJsonString(), "[^\u4e00-\u9fa5_a-zA-Z0-9]+", "");
            var results = _cacheManager.GetCache("LawSearch").GetOrDefault(cachestr);
            if (results == null || !input.iscache)
            {
                //List<ISort> orders = new List<ISort>();
                //ISort sort1 = new FieldSort() { Field = "effective_date", Order = Nest.SortOrder.Descending, UnmappedType = FieldType.Date };
                //ISort sort = new FieldSort() { Field = "order", Order = Nest.SortOrder.Ascending, UnmappedType = FieldType.Long };
                //orders.Add(sort1);
                //orders.Add(sort);


                var request = new SearchRequest("lawdetail")
                {
                    From = 0,
                    Size = 9999,
                    Source = new SourceFilter()
                    {
                        Includes = new string[] { "id", "name", "tiaoint", "tiao", "order", "outerHtml", "effective_date", "lawdetailotherinputdtos" }
                        //Includes = new string[] { "eventid", "eventname" },
                        //Excludes = new string[] { "roginalid", "description" }
                    },
                    //Sort = orders
                };

                ///////////////////////
                QueryContainer querycontainer = SearchParem(input);
                if (querycontainer != null)
                {
                    request.Query = querycontainer;
                }
                var his = await _abpElasticSearch.SearchAsync<LawDetailSearchOutDTO, string>(request);
                string hightli = _Helpers.returnChina(input.ToJsonString().Replace(":", "的"));
                List<LawDetailSearchOutDTO> lawdetailsearchoutdtos = new List<LawDetailSearchOutDTO>();

                if (!string.IsNullOrEmpty(hightli) && input.ishilhlit == 1)
                {
                    //List<string> x = _abpElasticSearch.EsClient.Indices.Analyze(x => x.Analyzer("ik_smart").Text(hightli).Pretty()).Tokens.Select(p => p.Token).ToList();
                    foreach (var item in his.Hits)
                    {
                        LawDetailSearchOutDTO enty = (LawDetailSearchOutDTO)item.Source;
                        if (!string.IsNullOrEmpty(enty.Id))
                        {
                            //_Helpers.ReturnhightTags(enty, x);
                        }
                        if (enty.lawdetailotherinputdtos != null && enty.lawdetailotherinputdtos.Count > 0)
                        {
                            enty.lawdetailotherinputdtos.ForEach(p => p.content.Replace("法信", "律格尔"));
                            enty.lawdetailrelation = enty.lawdetailotherinputdtos.Where(p => p.type == "法律关联法条").ToList();
                            enty.lawdetailexplain = enty.lawdetailotherinputdtos.Where(p => p.type == "释义" && p.content.Length > 255).ToList();
                            enty.lawdetailcontinue = enty.lawdetailotherinputdtos.Where(p => p.type == "沿革信息" && p.content.Length > 0).ToList();
                            enty.lawdetailotherinputdtos = new List<LawDetailOtherInputDTO>();
                        }

                        lawdetailsearchoutdtos.Add(enty);
                    }
                }
                else
                {
                    foreach (var item in his.Hits)
                    {
                        LawDetailSearchOutDTO enty = (LawDetailSearchOutDTO)item.Source;
                        if (enty.lawdetailotherinputdtos != null && enty.lawdetailotherinputdtos.Count > 0)
                        {
                            enty.lawdetailotherinputdtos.ForEach(p => p.content.Replace("法信", "律格尔"));
                            enty.lawdetailrelation = enty.lawdetailotherinputdtos.Where(p => p.type == "法律关联法条").ToList();
                            enty.lawdetailexplain = enty.lawdetailotherinputdtos.Where(p => p.type == "释义").ToList();
                            enty.lawdetailcontinue = enty.lawdetailotherinputdtos.Where(p => p.type == "沿革信息").ToList();
                            enty.lawdetailotherinputdtos = new List<LawDetailOtherInputDTO>();
                        }
                        lawdetailsearchoutdtos.Add(enty);
                    }
                }
                _cacheManager.GetCache("LawSearch").Set(cachestr, lawdetailsearchoutdtos.OrderBy(p => p.order).ToList(), new TimeSpan(60, 0, 0, 0));

                return lawdetailsearchoutdtos.OrderBy(p => p.order).ToList();
            }
            else
            {
                return (List<LawDetailSearchOutDTO>)results;
            }
        }
        private QueryContainer SearchParem(LawDetailSearchInDTO input)
        {

            //public string name { get; set; } //= 中华人民共和国民法典
            //public List<string> pid { get; set; } //
            //public List<string> tiaoint { get; set; } //": "151",
            //public List<string> tiao { get; set; } //": "第一百一十五条",

            QueryContainer request = new QueryContainer();
            bool isnull = true;

            if (!string.IsNullOrEmpty(input.name))
            {
                isnull = false;
                string Alianame = input.name.Replace("(", "（").Replace(")", "）").Replace(" ", "");
                Alianame = Regex.Replace(Alianame, "（.*?）", "");
                request = request &&
                new MatchQuery
                {
                    Query = Alianame,
                    Field = new Field("name"),
                    Operator = Operator.And,
                    Analyzer = "ik_max_word"
                };
            }
            if (input.pid != null && input.pid.Count > 0)
            {
                isnull = false;
                QueryContainer qc = new QueryContainer();
                foreach (var item in input.pid)
                {
                    qc = qc || new TermQuery
                    {
                        Field = new Field("pid"),
                        Value = item.Replace(" ", "")
                    };
                }
                request = request && (qc);
            }
            if (input.tiaoint != null && input.tiaoint.Count > 0)
            {
                isnull = false;
                QueryContainer qc = new QueryContainer();
                foreach (var item in input.tiaoint)
                {
                    qc = qc || new TermQuery
                    {
                        Field = new Field("tiaoint"),
                        Value = item.Replace(" ", "")
                    };
                }
                request = request && (qc);
            }
            if (input.tiao != null && input.tiao.Count > 0)
            {
                isnull = false;
                QueryContainer qc = new QueryContainer();
                foreach (var item in input.tiao)
                {
                    qc = qc || new TermQuery
                    {
                        Field = new Field("tiao"),
                        Value = item.Replace(" ", "")
                    };
                }
                request = request && (qc);
            }

            if (isnull)
            {
                return null;
            }

            return request;
        }


        #endregion


        /// <summary>
        /// 获取法条内容
        /// </summary>
        /// <param name="name"></param>
        /// <param name="tiao"></param>
        /// <returns></returns>
        [RemoteService(false)]
        public string GetLawByNameAndTiao2(string name, string tiao)
        {
            return "";
            LawDetailSearchInDTO input = new LawDetailSearchInDTO();
            input.name = name;
            input.tiao = new List<string>();
            input.tiao.Add(tiao);
            List<LawDetailSearchOutDTO> d = LawDetailSearch2(input);
            return d.ToJsonString();
        }



        /// <summary>
        /// 获取法条内容
        /// </summary>
        /// <param name="name"></param>
        /// <param name="tiao"></param>
        /// <returns></returns>
        public async Task<List<LawDetailSearchOutDTO>> GetLawByNameAndTiaoAsync(string name, string tiao)
        {
            List<LawDetailSearchOutDTO> d = new List<LawDetailSearchOutDTO>();
            if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(tiao))
            {
                LawDetailSearchInDTO input = new LawDetailSearchInDTO();
                input.name = System.Web.HttpUtility.UrlDecode(name).Replace("年","");
                input.tiao = new List<string>();
                input.tiao.Add(tiao);
                d = await LawDetailSearchAsync(input);
                return d.OrderByDescending(p => p.effective_date).ToList(); ;
            }
            return d.OrderByDescending(p=>p.effective_date).ToList();

        }
        /// <summary>
        /// 获取法律内容
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public async Task<List<LawSearchOutDTO>> GetShortLawByName(string name)
        {
            LawSearchParamDto input = new LawSearchParamDto();
            input.Data = new LawSearchInDTO();
            input.Data.name = System.Web.HttpUtility.UrlDecode(name).Replace("年", "");
            input.isagg = false;
            LawSearchOutParamDto d = await LawSearchAsync(input);
            return d.Datas.OrderByDescending(p=>p.effective_date).ToList();
        }

        
    }
}
